package com.shinowit.tools;

import java.sql.Connection;
import java.util.Properties;

import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;

/**
 * 
 * 类说明：针对于Executor的拦截器
 * 
 * @author lzy
 * @version Version 1.0
 * @since JDK 1.6
 */
@Intercepts(value = { @Signature(method = "prepare", type = StatementHandler.class, args = {
		Connection.class, Integer.class }) })
@Component
public class EnhancedCachingExecutor implements Interceptor {

	// private Logger log = Logger.getLogger(EnhancedCachingExecutor.class);

	private String databaseType;

	public Object intercept(Invocation invocation) throws Throwable {
		String name = invocation.getMethod().getName();
		Object result = null;
		if ("prepare".equalsIgnoreCase(name)) {// 根据特定条件执行分页查询
			result = PageUtils.executePage(invocation, databaseType);
		}
		return result;
	}

	public Object plugin(Object target) {
		if (target instanceof StatementHandler
				|| target instanceof ResultSetHandler) {
			return Plugin.wrap(target, this);

		} else {
			return target;
		}
	}

	public void setProperties(Properties properties) {
		this.databaseType = properties.getProperty("databaseType");
	}

	/**
	 * @return the databaseType
	 */
	public String getDatabaseType() {
		return databaseType;
	}

	/**
	 * @param databaseType
	 *            the databaseType to set
	 */
	public void setDatabaseType(String databaseType) {
		this.databaseType = databaseType;
	}
}
